<template>
	<view class="productManagementPage">
		<view class="productManagemenTop">
			<view class="font-weight_bold margin-top_40rpx">
				商品标题
			</view>
			<view class="edit flex-start-center  margin-top_16rpx">
				<input class="uni-input" v-model="form.name" placeholder="请写明品牌、商品名、属性、等关键信息 " />


			</view>
			<sunui-upimg1 :border="'1px dashed #bfbfbf'" :formData="imgFormData" :storageMode="storageMode"
				:header="header" :size="['200rpx', '200rpx']" btnName="上传图片" :uploadServerUrl="upPicUrl"
				ref="selectimgandupload1" @uploaded="imgLoaded1" @change="imgsChange1" :maxFileNumber="4"><template
					v-slot:icon>
					<uni-icons type="camera-filled" color="#1890FF" size="40"></uni-icons>
				</template></sunui-upimg1>
			<view class=" myNmae flex-between margin-top_40rpx ">
				<view class="font-weight_bold ">
					商品副标题
				</view>
				<view class="">
					<input class="uni-input" v-model="form.title" placeholder="请填写副标题" />
				</view>


			</view>
			<view class="flex-between margin-top_40rpx">
				<view class="font-weight_bold ">
					商品类目
				</view>
				<picker mode="selector" @change='classifyFn' :range="classifyList" :range-key="'text'">
					<view class="flex">
						<text>{{classify}}</text>
						<uni-icons type="right" size="15"></uni-icons>
					</view>
				</picker>

			</view>

			<!-- <view class="font-weight_bold margin-top_40rpx">
				商品详情
			</view>

			<view class="margin_20rpx_0">
				
			</view> -->


		</view>
		<view class="productManagementSelect">
			<!-- <view class="flex-between  ">
				<view class="font-weight_bold ">
					商品模式
				</view>
				<view style="color: rgb(153, 153, 153);" class="flex">
					<picker mode="selector" @change='saleFn' :range="saleList" :range-key="'text'">
						<view class="flex">
							{{sale}} <uni-icons type="right" color="rgb(153, 153, 153)" size="15"></uni-icons>
						</view>
					</picker>

				</view>

			</view> -->

			<view class="flex-between margin-top_40rpx ">
				<view class="font-weight_bold ">
					发货时间
				</view>
				<view style="color: rgb(153, 153, 153);" class="flex">
					<picker mode="selector" @change='deliveryTimeFn' :range="deliveryTimeList" :range-key="'text'">
						<view class="flex">
							{{timeDec}} <uni-icons type="right" color="rgb(153, 153, 153)" size="15"></uni-icons>
						</view>
					</picker>

				</view>

			</view>
			<view class="flex-between margin-top_40rpx ">
				<view class="font-weight_bold ">
					是否积分购买
				</view>
				<view class="">
					<switch style="transform:scale(0.7)" :checked="isPoints" @change="switch1Change" />
					<!-- <input class="uni-input" v-model="changeValue" placeholder="请输入该规格所需积分" /> -->
				</view>


			</view>

			<view class="flex-between margin-top_40rpx ">
				<view class="font-weight_bold ">
					是否开启会员等级
				</view>

				<switch style="transform:scale(0.7)" :checked="form.is_swich_level==1?true:false" @change="switchlevel" />
				<!-- <input class="uni-input" v-model="changeValue" placeholder="请输入该规格所需积分" /> -->
			</view>
			<view class="margin-top_20rpx">
				<text style="color: rgb(255, 0, 0);">备注：如果开启将会针对单个商品的的折扣</text>
			</view>
			<view class="" v-if="form.is_swich_level==1">
				<view v-for="(item, index) in form.discount" :key="index" class="myNmae flex-between  margin-top_40rpx">

					<view class="font-weight_bold ">
						<picker mode="selector" @change='e=>levelFn(e
							,index)' :range="levelList" :range-key="'text'">
							<view class="flex">
								{{item.level?item.level:'选择会员等级'}}
								<uni-icons type="right" size="15"></uni-icons>
							</view>
						</picker>
					</view>
					<view class="flex">
						<input class="uni-input" type="number" maxlength="3" v-model="item.discount"
							placeholder="请填写折扣价" />

						<view class="margin-left_10rpx">
							<button class="mini-btn" @click="add()" v-if="0==index" type="primary">+</button>

							<button type="primary" class="mini-btn" @click="subtract(index)" v-else>-</button>
						</view>
					</view>


				</view>
				<view class="margin-top_20rpx">
					<text style="color: rgb(255, 0, 0);">备注：以百分比形式(如填写95等于购买商品享受9.5折优惠)</text>
				</view>
			</view>
			<view class=" myNmae flex-between margin-top_40rpx ">
				<view class="font-weight_bold ">
					售卖价
				</view>
				<view class="">
					<input class="uni-input" v-model="form.price" placeholder="请填写售卖价" />
				</view>


			</view>
			<view class=" myNmae flex-between margin-top_40rpx ">
				<view class="font-weight_bold ">
					市场价
				</view>
				<view class="">
					<input class="uni-input" v-model="form.market_price" placeholder="请填写市场价" />
				</view>


			</view>
			<view class="myNmae flex-between margin-top_40rpx ">
				<view class="font-weight_bold ">
					库存
				</view>
				<view class="">
					<input class="uni-input" v-model="form.inventory" placeholder="请填写库存" />
				</view>


			</view>
			<view class="margin-top_40rpx">
				<view class="flex-between">
					<view class="font-weight_bold">
						商品详情
					</view>
					<!-- 	<view style="color: rgb(153, 153, 153);" class="">
						请选择
						<uni-icons type="right" size="15"></uni-icons>
					</view> -->

				</view>
				<view style="color: rgb(153, 153, 153);" class="margin-top_20rpx">
					<lRichTextEditor v-model="form.desc" @change="getChange">
					</lRichTextEditor>
				</view>
			</view>
			<view class="save flex" @click="submitProduct()">
				{{isEdit?'编辑':'保存'}}
			</view>
		</view>

	</view>
</template>

<script>
	import {
		object2Url
	} from '@/utils/trans';
	export default {
		components: {

		},
		data() {
			return {
				tabIndex: 4,
				changeValue: '',
				imgFormData: null,
				ossInfo: null,
				upPicUrl: null,
				imgStr: [],
				form: {
					// 商品名称

					name: '',
					// 商品图片
					host_img: '',
					// 商品详情
					desc: '',

					// 发货时间
					delivery_time: '',
					// 价格
					price: '',
					// 市场价格
					market_price: '',
					// 分类id
					classify_id: '',
					// 商品模式 1现货 2 预售
					// sale_mode: '',
					// 是否积分购买 1允许 2 不允许
					buying_pattern: '2',
					// 库存
					inventory: "",
					//1 开启  0 关闭
					is_swich_level:1,
					title: '',
					// 折扣
					discount: [{
						level_id: '',
						discount: '',
						level: '选择会员等级'
					}]
				},
				classify: '请选择',
				sale: '请选择',
				timeDec: '请选择',
				level: '会员等级',
				// 分类列表
				classifyList: [],
				// 会员列表
				levelList: [],
				// 是否购买积分
				isPoints: false,
				isEdit: false,
				// 1 开启 2 关闭
				isMembershipLevel: 1,
				saleList: [{
						text: '现货现卖',
						value: "1"
					},
					{
						text: '预售',
						value: "2"
					}
				],
				deliveryTimeList: [{
						text: '24小时',
						value: "24小时"
					},
					{
						text: '48小时',
						value: "48小时"
					},
					{
						text: '72小时',
						value: "72小时"
					}
				],
				storageMode: "2",
				header: null,
				timeDate: '',
				allArr: [{
					text: '全部',
					value: '0'
				}],
				token: uni.getStorageSync('login').token,
			}
		},
		onLoad(options) {
			if (options.id) {

				this.form.id = ''

				this.$sun.assignObject(this.form, {
					...options
				})
				this.isPoints = options.buying_pattern = 1 ? true : false
				// this.isMembershipLevel = (uni.getStorageSync('isMembershipLevel'))

				let imgStr1 = options.host_img
				if (imgStr1.length) {
					if (imgStr1.includes(',')) {
						console.log('字符串中包含逗号');
						// 包含的进行slice(',') 分割

						this.imgStr1 = imgStr1.split(',').map((item) => item.trim());

						this.$nextTick(() => {
							this.$refs.selectimgandupload1.setItems(this.imgStr1);
						})
					} else {
						console.log('字符串中不包含逗号');
						this.imgStr1 = imgStr1.split();
						this.$nextTick(() => {
							this.$refs.selectimgandupload1.setItems(this.imgStr1);
						})
					}

				}


				// 编辑 商品模式
				// const couponType = this.saleList.find((item) => {
				// 	return item.value == this.form.sale_mode
				// })

				// this.sale = couponType.text
				// 发货时间
				const deliveryTime = this.deliveryTimeList.find((item) => {
					return item.value == this.form.delivery_time
				})

				this.timeDec = deliveryTime.text
				this.isEdit = true
				console.log(this.form)

			}
			this.init()
		},
		onShow() {
			this.$at.releaseKey('submit');
		},
		methods: {
			// 商品详情接口 获取会员等级
			async goodsInfoFn(id) {

				const result = await this.$http.post({
					url: this.$api.goodsInfo,
					data: {
						id: id

					},
					headers: {
						'Authorization': `Bearer ${this.token}`
					}

				})

				if (result.code == 0) {

					console.log(result)
					if (result.data.discount.length) {
						this.form.discount = result.data.discount
						if (this.levelList.length) {




							this.form.discount = result.data.discount.map((item) => {
								const levelType = this.levelList.find((items) => {
									return items.value == item.level_id
								})

								return {
									discount: item.discount,
									level_id: item.level_id,
									level: levelType.text,
									create_time: item.create_time,
									goods_id: item.goods_id,
									id: item.id,
									update_time: item.update_time

								}
							})
							console.log(this.form.discount)
						}

					} else {
						this.form.discount = [{
							level_id: '',
							discount: '',
							level: '选择会员等级'
						}];
					}


				} else {
					this.$sun.toast(result.msg, 'none')
				}
			},


			switch1Change(e) {
				console.log(e)
				this.isPoints = e.detail.value
				// true 是允许积分购买
				if (this.isPoints) {
					this.form.buying_pattern = 1
				} else {
					this.form.buying_pattern = 2
				}

			},
			switchlevel(e) {
				console.log(e.detail.value)
				if (e.detail.value) {
					this.form.is_swich_level = 1
				} else {
					this.form.is_swich_level = 0
				}
			},
			// 添加字幕
			add() {
				if (this.form.discount.length >= this.levelList.length) {
					this.$sun.toast('添加会员等级已经到达上限', 'none')
					return false
				}
				let content = {
					discount: '',
					level_id: '',
					level: '选择会员等级'
				}
				this.form.discount.push(content)
				console.log('this.form.discount', this.form.discount, this.form.discount.length)
			},
			//删除字幕
			subtract(index) {
				this.form.discount.splice(index, 1)
				console.log("this.form.discount", this.form.discount, this.form.discount.length)
			},
			async init() {
				// 查询分类列表
				const result = await this.$http.post({
					url: this.$api.classifyList,
					data: {


					},
					headers: {
						'Authorization': `Bearer ${this.token}`
					}

				})
				if (result.code == 0) {
					const classifyData = result.data.list.map((item) => {
						return {
							text: item.name,
							value: item.id
						}
					})
					this.classifyList = [...classifyData]

					if (this.isEdit) {
						// 编辑 商品类目
						const classify = this.classifyList.find((item) => {
							return item.value == this.form.classify_id
						})
						this.classify = classify.text
					}

				} else {
					this.$sun.toast(result.msg, 'none')
				}
				// 查询会员列表
				const res = await this.$http.post({
					url: this.$api.levelList,
					data: {


					},
					headers: {
						'Authorization': `Bearer ${this.token}`
					}

				})
				if (res.code == 0) {
					const classifyData = res.data.list.map((item) => {
						return {
							text: item.name,
							value: item.id
						}
					})
					this.levelList = [...classifyData]

					if (this.isEdit) {
						this.goodsInfoFn(this.form.id)
					}

				} else {
					this.$sun.toast(res.msg, 'none')
				}
			},
			getChange(e) {
				console.log(e)
				this.form.desc = e

			},
			saleFn(e) {
				this.form.sale_mode = this.saleList[e.detail.value].value

				this.sale = this.saleList[e.detail.value].text
			},

			classifyFn(e) {

				this.form.classify_id = this.classifyList[e.detail.value].value
				console.log(this.form.classify_id)
				this.classify = this.classifyList[e.detail.value].text
			},
			levelFn(e, index) {
				console.log(e, index)
				this.form.discount[index].level_id = this.levelList[e.detail.value].value


				this.form.discount[index].level = this.levelList[e.detail.value].text

				console.log(this.form.discount)
			},
			deliveryTimeFn(e) {
				this.form.delivery_time = this.deliveryTimeList[e.detail.value].value

				this.timeDec = this.deliveryTimeList[e.detail.value].text
			},
			// niuyun
			niuyunLoop(file, i) {
				if (i >= file.length) {
					return;
				}
				console.log(file)
				let fileUrl = file[i].url;
				this.upPicUrl = this.$api.qnyOssSignature;
				let filesNmae = 'nmoBackground_01.png'; // this.timeDate + 'png'
				this.imgFormData = {
					file: fileUrl,
					getsize: file.size,
					getContentType: ['image/png', 'image/jpeg'],
					getoriginalfilename: filesNmae,
					getName: filesNmae
				};
				this.$nextTick(() => {
					this.$refs.selectimgandupload1.upload(); //图片上传
				});
				setTimeout(() => {
					this.niuyunLoop(file, i + 1);
				}, 2500);

			},
			delayLoop(file, i) {
				if (i >= file.length) {
					return;
				}
				console.log(file.length + '===chand1')
				if (file.length) {
					let fileUrl = file[i].url;
					console.log(fileUrl)
					this.timeDate = new Date().getTime();
					let markIndex = fileUrl.lastIndexOf('.');
					this.suffix = fileUrl.substring(markIndex); //后缀


					this.imgFormData = {
						name: this.timeDate + this.suffix,
						key: this.timeDate + this.suffix, //上传图片的名字和路径（默认路径根目录，自定义目录：xxx/xxx.png）
						policy: this.ossInfo.policy,
						OSSAccessKeyId: this.ossInfo.accessId,
						success_action_status: '200',
						signature: this.ossInfo.signature
					};
					this.header = {
						'Access-Control-Allow-Origin': '*',
						'x-oss-callback-Authorization': 'access_token'
					};
					this.$nextTick(() => {
						this.$refs.selectimgandupload1.upload(); //图片上传
					});

				} else {
					this.form.host_img = ''
				}

				setTimeout(() => {
					this.delayLoop(file, i + 1);
				}, 500);
			},
			// 上传图片返回
			imgLoaded1(e) {
				console.log(e)

				this.img = [];
				for (let i = 0; i < e.length; i++) {
					this.img.push(e[i].url);
				}


				this.imgStr = this.img

				this.form.host_img = this.imgStr.length === 1 ? this.imgStr[0].toString() : this.imgStr
					.join(',');
			},
			// “上传图片”发生改变
			imgsChange1(file) {

				console.log('上传发生改变this.storageMode1111============', this.storageMode, '参数file', file);
				// 如果是2 上传  阿里云 3  七牛云
				if (file.length) {
					this.upPicUrl = this.$api.upload;
					let filesNmae = 'nmoBackground_01.png'; // this.timeDate + 'png'
					this.imgFormData = {
						file: file,
						getsize: file.size,
						getContentType: ['image/png', 'image/jpeg'],
						getoriginalfilename: filesNmae,
						getName: filesNmae
					};
					this.$nextTick(() => {
						this.$refs.selectimgandupload1.upload(); //图片上传
					});
				} else {
					this.form.host_img = '',
						this.imgStr = []
				}
			},
			// 阿里云上传
			async userOssSignature(file) {
				// 文件名
				if (file.length) {
					console.log('this阿里云上传进入=======');
					const ts = new Date().getTime();
					const us = {
						ts
					};
					let url = 'https://yjykmaster.admin168.net/door-massage/massage/upload/alyOssSignature' +
						`${object2Url(us)}`;
					const res = await this.$http.get({
						url: url,
						data: {
							us: us
						}
					});
					this.ossInfo = res.data;
					this.upPicUrl = this.ossInfo?.host;
					// 获取上传图片名称和后缀
					this.delayLoop(file, 0);
				} else {
					this.form.host_img = '',
						this.imgStr = []
				}




			},
			customLogic(a, b) {
				if (!a && !b) {
					return true; // 两个都是 false
				} else if (a && b) {
					return true; // 两个都是 true
				} else {
					return false; // 至少有一个是 false
				}
			},
			submitProduct() {

				this.$at.uniDoFunc({
					key: 'submit',
					success: async () => {
						this.$at.lockKey('submit');
						console.log(this.form)
						// 登录 需要进行判断当前账号密码 和账号归属店铺及角色是否又选择
						if (!this.form.name) {
							this.$sun.toast("请输入商品标题", 'none')
							this.$at.releaseKey('submit');
						} else if (!this.form.host_img) {
							this.$sun.toast("请选择商品图片", 'none')
							this.$at.releaseKey('submit');
						} else if (!this.form.classify_id) {

							this.$sun.toast("请选择商品分类", 'none')
							this.$at.releaseKey('submit');

						} else if (!this.form.delivery_time) {

							this.$sun.toast("请选择发货时间", 'none')
							this.$at.releaseKey('submit');

						} else if (!this.form.price) {

							this.$sun.toast("请填写售卖价", 'none')
							this.$at.releaseKey('submit');

						} else if (!this.form.inventory) {

							this.$sun.toast("请填写市场价", 'none')
							this.$at.releaseKey('submit');

						} else if (!this.form.inventory) {

							this.$sun.toast("请填写库存", 'none')
							this.$at.releaseKey('submit');

						} else {
							// if (this.form.discount.some(item => !item.level_id || !item.discount)) {
							// 	this.$sun.toast("请选择会员等级", 'none')
							// 	this.$at.releaseKey('submit');
							// 	return

							// uni.setStorageSync('isMembershipLevel', JSON.stringify(this.isMembershipLevel))
							let discountsWithoutLevel = this.form.discount.map(({
								level,
								...rest
							}) => rest);
							if (discountsWithoutLevel.length) {
								for (let i = 0; i < discountsWithoutLevel.length; i++) {
									const item = discountsWithoutLevel[i];
							
									if ((this.form.is_swich_level == 1)) {
										if (!item.level_id) {
											this.$sun.toast("请填写会员等级", 'none')
											this.$at.releaseKey('submit');

											return; // 提前结束循环并返回
										}
										if (!item.discount) {
											this.$sun.toast("请填写折扣价", 'none')
											this.$at.releaseKey('submit');

											return; // 提前结束循环并返回
										}
									} else {
										//   this.$message.error('会员等级折扣价都没填');
										discountsWithoutLevel = []

									}
									// 其他逻辑

								}
							} else {
								for (let i = 0; i < discountsWithoutLevel.length; i++) {
									const item = discountsWithoutLevel[i];

									if (!this.customLogic(item.level_id, item.discount)) {
										this.$sun.toast("请填写会员等级或者折扣价", 'none')
										this.$at.releaseKey('submit');

										return; // 提前结束循环并返回
									}

									// 其他逻辑
								}
							}
							this.form.discount = discountsWithoutLevel
							console.log((this.form))
							const saveOrUpdate = this.isEdit ? this.$api.editGoods : this.$api
								.addGoods;
							const res = await this.$http.post({
								url: saveOrUpdate,
								data: {

									...this.form
								},
								headers: {
									'Authorization': `Bearer ${this.token}`
								}

							})
							console.log(res)
							if (res.code == 0) {



								// 跳转到登录页面
								this.$at.releaseKey('submit');
								this.$sun.toast(res.msg, 'none')

								setTimeout(() => {
									this.$sun.navBack()
								}, 800)
							} else {
								this.$at.releaseKey('submit');
								this.$sun.toast(res.msg, 'none')
							}




						}
					}
				});

			}
		}
	}
</script>

<style lang="less">
	.myNmae {

		background-color: #fff;
		min-width: 50rpx;

		.avatar {
			width: 84rpx;
			height: 84rpx;
		}

		input {
			text-align: right;
		}

		.backgroundImg {

			height: 154rpx;


		}

	}

	.productManagementPage {
		.productManagementSelect {
			// /deep/.uni-input {
			// 	// text-align: end;
			// 	width: 90px;
			// }

			margin-top: 18rpx;
			padding: 40rpx;
			background-color: #fff;

			.save {
				margin-top: 40rpx;

				height: 108rpx;
				border-radius: 128rpx;

				background: rgb(89, 147, 249);
				color: rgb(255, 255, 255);
				font-size: 32rpx;
			}

		}

		.productManagemenTop {
			padding: 40rpx;
			background-color: #fff;

			.edit {

				height: 88rpx;




			}

			.uni-textarea {
				margin-top: 20rpx;

				textarea {
					width: 100%;
					box-sizing: border-box;
					border-radius: 10px;


					border-radius: 10px;
					background-color: #f6f6f6;
					padding: 15rpx 15rpx 15rpx 15rpx;
				}
			}
		}
	}

	page {
		background: #f6f6f6;
	}
</style>